﻿@using MvcDataTables
@model DataTableModel

<table id="@Model.Id">
    <thead>
        <tr id="Headers">
            @foreach (var column in Model.ReadableColumns)
            {
                <th>@column</th>
            }
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>
<br />
<br />
@if (Model.IsEditable && Model.IsAddable)
{
    <div class="add_delete_toolbar" />    
    @Html.Raw(Model.AddableHtml)
    @Html.Raw(Model.AddableHtmlForEnumeratedTypes)
}

<script type="text/javascript">    
    $.ajaxSetup({ cache: false });

    $(document).ready(function () {
        var table = $('#@Model.Id').dataTable({
            "bProcessing": true,
            "bStateSave": true,
            "bServerSide": true,
            "bPaginate": true,
            "sAjaxSource": "@Html.Raw(Model.GetSource)",
            "fnServerData": function (sSource, aoData, fnCallback) {
                $.getJSON(sSource, aoData, function (json) {
                    if (json["aoColumns"] != null) {
                        table.fnSettings().aoColumns = [];
                        var headers = $("#Headers");
                        headers.empty();
                        var jsonColumns = json["aoColumns"];
                        for (var index = 0; index < jsonColumns.length; index++) {
                            var header = json["aoColumns"][index]["sTitle"];
                            var th = document.createElement('th');
                            th.innerHTML = header;
                            headers.append(th);
                            table._fnAddColumn(table.fnSettings(), th);
                        }                                             
                    }
                    fnCallback(json);
                });
            }
        })
        @if (Model.IsEditable)
        {
            <text>@Html.Raw(Model.EditableHtml)</text>
        };
    });

@if (Model.IsMasterDetail)
{
    <text>
    $(document).on("click", '#@Model.Id tbody td', function () {
        var th = $(this).closest('table').find('th').eq($(this).index());
        var header = th.text();
        var enumeratedColumns = GetEnumeratedColumns();
        if ($.inArray(header, enumeratedColumns) == -1) return;
        //Hide the add button (because we clicked on another enumerated column)
        var addButton = $("#AddButton");
        if (addButton.length != 0)
        {
            $("#AddButton").unbind('click');
            $("#AddButton").hide();
        }
        //Get the row and table to collapse/expand the details
        var tr = $(this).closest('tr')[0];
        var table = $("#@Model.Id").dataTable();
        if (table.fnIsOpen(tr)) {
            table.fnClose(tr);
        }
        else {
            @Html.Raw(Model.MasterDetailJavascript)
            var detail = $(tableHtml).dataTable({
                "bProcessing": true,
                "bServerSide": true,
                "bPaginate": true,
                "sAjaxSource": ajaxSource,
                "fnServerData": function (sSource, aoData, fnCallback) {
                    //TODO: Functionalize this
                    var htmlTable = table[0];
                    SerializeRowToArray(htmlTable, tr, aoData);
                    $.getJSON(sSource, aoData, function (json) {
                        fnCallback(json);
                    });
                }
            });            
            table.fnOpen(tr, detail, null);
            //Create the add button
            addButton = $("#AddButton");
            if (addButton.length == 0) {
                var oAddDeleteToolbar = $(".add_delete_toolbar");
                oAddDeleteToolbar.append("<button id='AddButton' class='add_row'/>");
                addButton = $("#AddButton");
            }
            else {
                addButton.show();
            }
            addButton.html(action.replace("/", ""));
            //Get the invisible form specific to this header (should always be there for enumerated types, throw exception otherwise)
            var addForm = $("#" + header);
            addButton.click(function ()
            {
                addForm.dialog({
                    autoOpen: false, modal: true, title: "Add " + header,
                    buttons: {
                        "Ok": function OnOk(event) {
                            var addForm = $(this);
                            if (addForm.valid()) {
                                var params = addForm.serialize();
                                $.ajax({
                                    'url': controller + action,
                                    'data': params,
                                    'type': "POST",
                                    "dataType": "text"
                                }).done(function () { table.fnReloadAjax(); });
                            }
                            addForm.dialog("close");
                        }, "Cancel": OnCancel
                    }
                });
                addForm.dialog('open');
            });
        }
    });

    function OnCancel(event) {
        var addForm = $(this);
        addForm.dialog("close");
    }
    </text>
}
    
@if (Model.IsEditable)
{
    <text>
    @Html.Raw(Model.GetEditableClientsideFunctions)
    </text>
}

    //See fnReloadAjax code by Allan Jardine at http://www.datatables.net/plug-ins/api
    $.fn.dataTableExt.oApi.fnReloadAjax = function (oSettings, sNewSource, fnCallback, bStandingRedraw) {
        if (typeof sNewSource != 'undefined' && sNewSource != null) {
            oSettings.sAjaxSource = sNewSource;
        }
        // Server-side processing should just call fnDraw
        if (oSettings.oFeatures.bServerSide) {
            this.fnDraw();
            return;
        }
        this.oApi._fnProcessingDisplay(oSettings, true);
        var that = this;
        var iStart = oSettings._iDisplayStart;
        var aData = [];

        this.oApi._fnServerParams(oSettings, aData);

        oSettings.fnServerData.call(oSettings.oInstance, oSettings.sAjaxSource, aData, function (json) {
            /* Clear the old information from the table */
            that.oApi._fnClearTable(oSettings);

            /* Got the data - add it to the table */
            var aData = (oSettings.sAjaxDataProp !== "") ?
                that.oApi._fnGetObjectDataFn(oSettings.sAjaxDataProp)(json) : json;

            for (var i = 0 ; i < aData.length ; i++) {
                that.oApi._fnAddData(oSettings, aData[i]);
            }

            oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();

            if (typeof bStandingRedraw != 'undefined' && bStandingRedraw === true) {
                oSettings._iDisplayStart = iStart;
                that.fnDraw(false);
            }
            else {
                that.fnDraw();
            }

            that.oApi._fnProcessingDisplay(oSettings, false);

            /* Callback user function - for event handlers etc */
            if (typeof fnCallback == 'function' && fnCallback != null) {
                fnCallback(oSettings);
            }
        }, oSettings);
    };
</script>